package com.bianmin.Controller;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import com.bianmin.Data.Result;
import com.bianmin.Data.ResultCode;
import com.bianmin.Mapper.ArticleMapper;
import com.bianmin.Mapper.OrderMapper;
import com.bianmin.Mapper.QuantityRecordsMapper;
import com.bianmin.Mapper.UserMapper;
import com.bianmin.Model.*;
import com.bianmin.coomen.AlyOssManager;
import com.bianmin.coomen.Util;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/article")
public class ArticleController {

    @Autowired
    private ArticleMapper mapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WxMaService wxService;

    @Autowired
    private UtilController utilController;

    @Autowired
    private QuantityRecordsMapper quantityRecordsMapper;

    @Autowired
    private OrderMapper orderMapper;


    //发布文章
    @PostMapping("add")
    public Result<Object> addArticle(@RequestBody Article article) {

        String content = article.getTitle() + article.getContent();
        boolean isOk = utilController.msgSecCheck(content);

        if (!isOk) {
            return Result.customError(1001,"输入内容部合法");
        }

        if (article.getId() != null) {
            //有id更新
            mapper.updateById(article);
        }else{
            //没有id创建
            article.setCreateTime(Util.currentTimeString());
            mapper.insert(article);
        }
        return new Result(ResultCode.RC200,null);
    }

    //文章列表
    @GetMapping("list")
    public Result<List<Article>> articleList(int page, int pageSize) {

        List<Article> data = new ArrayList<>();
        //如果是第0页。就获取一下置顶的数据。否则不获取
        if (page == 0) {
            List<Article> topArticleList = mapper.topArticleList();
            for (Article article : topArticleList) {
                article.setOnTop(true);
            }
            data.addAll(topArticleList);
        }

        List<Article> articles = mapper.articleList(page * pageSize, pageSize);
        data.addAll(articles);
        //根据id倒序
        return Result.success(data);
    }

    //搜索文章
    @GetMapping("search")
    public Result<List<Article>> searchArticle(String keyWord){
        String s = "%" + keyWord + "%";
        List<Article> articles = mapper.searchArticle(s);
        return Result.success(articles);
    }

    //删除文章
    @PostMapping("delete")
    public Result<String> deleteArticle(@RequestBody Map<String,Object> map) {
        String id = map.get("id").toString();

        Article article = mapper.articleDetail(id);
        AlyOssManager ossManager = new AlyOssManager();
        ossManager.deleteFile(article.getPics());

        mapper.deleteComments(id);
        boolean r = mapper.deleteArticle(id);
        return r ? Result.success("") : Result.error(ResultCode.RC1001);
    }

    //收藏 / 取消收藏文章
    @PostMapping("collection")
    public Result<String> collectionArticle(@RequestBody Map<String,Object> map) {
        boolean r;
        //有id时，为取消收藏。否额为收藏
        String str = "";
        if (map.containsKey("id")) {
            String id = map.get("id").toString();
           r = mapper.unCollectionArticle(id);
           str = "取消成功";
        }else{
            String articleId = map.get("articleId").toString();
            String userId = map.get("userId").toString();
           r = mapper.collectionArticle(userId,articleId);
           str = "收藏成功";
        }
        return r ? Result.success(str) : Result.error(ResultCode.RC1001);
    }


    //添加评论
    @PostMapping("commentAdd")
    public Result<String> addComment(@RequestBody Comment comment) {

        boolean isOk = utilController.msgSecCheck(comment.getContent());

        if (!isOk) {
            return Result.customError(1001,"输入内容不合法");
        }


        String time = Util.currentTimeString();
        boolean r = mapper.commentArticle(comment.getArticleId(), comment.getContent(), comment.getUserId(), time);

        Map<String, String> map = mapper.queryOpenIdWithArticleId(comment.getArticleId(),comment.getUserId());
        String openId = map.get("openId");
        String name = map.get("name");
        String content = comment.getContent();
        String title = map.get("title");

        //获取发帖人的id
        String uid = mapper.queryUserIdWithArticleId(comment.getArticleId());
        //如果评论人和发帖人不是同一个人。就发送推送消息，否则不发
        if (!uid.equals(comment.getUserId())) {
            sendMsgTo(openId,title,content,name, comment.getArticleId());
        }

        return r ? Result.success("") : Result.error(ResultCode.RC1001);
    }

    //删除评论
    @PostMapping("commentDel")
    public Result<String> delComment(@RequestBody Map<String,String> map) {
        String id = map.get("id");
        boolean r = mapper.deleteComment(id);
        return r ? Result.success("") : Result.error(ResultCode.RC1001);
    }

    //文章详情
    @PostMapping("detail")
    public Result<Map<String,Object>> articleDetail(@RequestBody Map<String,String> map) {
        String id = map.get("id");
        String userId = map.get("userId");
        Map<String,Object> data = new HashMap<>();

        Article article = mapper.articleDetail(id);
        data.put("article",article);

        //设置收藏id
        String collectionId = mapper.queryArticleCollectionStatus(id,userId);
        if (collectionId != null) {
            article.setCollectionId(collectionId);
        }

        //查询收藏的数量
        Integer collectionCount = mapper.countForCollectionWithArticle(id);
        article.setCollectionCount(collectionCount);

        List<Comment> comments = mapper.articleComments(id);
        data.put("comments",comments);
        return Result.success(data);
    }


    //发送订阅消息
    private void sendMsgTo(String openId , String title, String content, String name, String articleId) {
        String page = "/pages/articleDetail/articleDetail?id=" + articleId;
        Map<String, String> map = new HashMap<>();
        map.put("thing4",title);
        map.put("thing2", content);
        map.put("name1",name);
        map.put("time3", Util.currentTimeString());
        WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
                .toUser(openId)
                .templateId("uxtRFL_jPobkKa9qJepHRzNAKbD5ISoEylYB3S3dl-I")
                .page(page)
                .build();
        // 设置将推送的消息
        map.forEach((k, v) -> {
            wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(k, v));
        });
        try {
            wxService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
            System.out.println(e.getError());
        }

    }

    /*
    * 置顶事件
    * {
    *   userId:String
    *   articleId:String
    * }
    * */
    @PostMapping("articleTopWithQuantity")
    public Result<Object> articleTopWithQuantity(@RequestBody Map<String,Object> map) {
        String userId = map.get("userId").toString();
        User user = userMapper.queryUserWithUserId(Integer.parseInt(userId));
        //积分足够的情况下。可以直接置顶，否则抛出异常
        if (user.getQuantity() >= 10) {
            String articleId = map.get("articleId").toString();
            Article article = mapper.articleDetail(articleId);
            Integer topTime = article.getTopEndTime();
            System.out.println(topTime);

            if (topTime != null) {
                if (topTime > Util.currentTimesStamp()) {
                    topTime += 3600;
                }else{
                    long l = Util.timeStringForafterHour(1);
                    topTime = Math.toIntExact(l);
                }
            }else{
                long l = Util.timeStringForafterHour(1);
                topTime = Math.toIntExact(l);
            }
            article.setTopEndTime(topTime);
            mapper.updateById(article);

            //扣除积分
            user.setQuantity(user.getQuantity() - 10);
            userMapper.updateById(user);

            //添加记录
            QuantityRecords records = new QuantityRecords();
            records.setRecord("置顶扣除 10 积分");
            records.setUserId(Integer.valueOf(userId));
            records.setCreateTime(Util.currentTimeString());
            quantityRecordsMapper.insert(records);

            return Result.success(null);
        }else{
            return Result.customError(1001,"积分不足");
        }
    }


}
